﻿using Abp.Application.Services.Dto;
using Abp.Domain.Repositories;
using Camc.Quality.Bop.Dto;
using Camc.Quality.Dto.TechniqueEntityDto;
using Camc.Quality.Quality;
using System;
using System.Collections.Generic;
using Abp.Linq.Extensions;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Camc.Quality.Business;
using Camc.Quality.Bop.TreeObject;
using Abp.UI;
using Camc.Quality.RecordTable.FormBase;
using Camc.Quality.ProcessRoute;
using Camc.Quality.DataDictionary;
using Microsoft.EntityFrameworkCore;
using NPOI.SS.Formula.Functions;
using Camc.Quality.WorkFlow;
using Camc.Quality.Dto.TableOutDto;
using Camc.Quality.RecordTable.FormClass;
using Camc.Quality.StoreManagement.StoragePut;
using System.Reflection;
using System.ComponentModel;
using Camc.Quality.SystemManagement;
using Camc.Quality.Authorization.Users;
using Abp.Authorization.Users;
using Camc.Quality.IOperationHistory;
using Camc.Quality.ProductionPlan;
using Camc.Quality.Common;

namespace Camc.Quality.Bop
{
    public class MoadifManageAppService : QualityAppServiceBase
    {
        private readonly IOperationHistoryAppService _iOperationHistoryAppService;
        private readonly IRepository<TechniqueEntity, Guid> _techniqueEntityRepository;
        private readonly IRepository<ProcessesEntity, Guid> _processesEntityRepository;
        private readonly IRepository<WorkStepEntity, Guid> _workStepEntityRepository;
        private readonly IRepository<BopNode, Guid> _bopNodeRepository;
        private readonly IRepository<BopDesc, Guid> _bopDescRepository;
        private readonly IRepository<ModifyManage, Guid> _modifyManageRepository;
        private readonly IRepository<TableBase, Guid> _tableBaseEntity;
        private readonly IRepository<ConvertFormBase, Guid> _convertFormBaseEntity;
        private readonly IRepository<ProcessLine, Guid> _processLineRepository;
        private readonly IRepository<Sys_Code, Guid> _sysCodeRepository;
        private readonly IRepository<RelationalCorrespond, Guid> _relationalCorrespondRepository;
        private readonly IRepository<LoadPieceEntity, Guid> _loadPieceRepository;
        private readonly IRepository<MakeResourcesEntity, Guid> _makeResourcesEntityRepository;
        private readonly IRepository<VideoEntity, Guid> _videoEntityRepository;
        public readonly IRepository<StoreStockContent, Guid> _storeStockContentRepsitory;
        private readonly IRepository<WorkFlowNode, Guid> _workFlowNodeRepository;
        private readonly WorkFlowAppService _workFlowAppService;
        private readonly IRepository<BusinessApplication, Guid> _businessApplicationRepository;
        private readonly IRepository<WorkAuditor, Guid> _workAuditorRepository;
        public readonly CodeFormatDescAppService _codeFormatDescAppServiceRepository;
        private readonly IRepository<User, long> _userRepository;
        private readonly IRepository<UserRole, long> _userRoleRepository;
        private readonly IRepository<ProductionScheduler, Guid> _productionSchedulerRepository;
        private ProcessManage _processManage { get; set; }


        public MoadifManageAppService(IRepository<TechniqueEntity, Guid> techniqueEntityRepository,
            IRepository<ProcessesEntity, Guid> processesEntityRepository,
            IRepository<WorkStepEntity, Guid> workStepEntityRepository,
            IRepository<BopNode, Guid> bopNodeRepository,
            IRepository<BopDesc, Guid> bopDescRepository,
            IRepository<ModifyManage, Guid> modifyManageRepository,
            IRepository<TableBase, Guid> tableBaseEntity,
            IRepository<ConvertFormBase, Guid> convertFormBaseEntity,
            IRepository<ProcessLine, Guid> processLineRepository,
            IRepository<Sys_Code, Guid> sysCodeRepository,
            ProcessManage processManage,
            IRepository<RelationalCorrespond, Guid> relationalCorrespondRepository,
            IRepository<LoadPieceEntity, Guid> loadPieceRepository,
            IRepository<MakeResourcesEntity, Guid> makeResourcesEntityRepository,
            IRepository<VideoEntity, Guid> videoEntityRepository,
            IRepository<StoreStockContent, Guid> storeStockContentRepsitory,
            WorkFlowAppService workFlowAppService,
            IRepository<WorkFlowNode, Guid> workFlowNodeRepository,
            IRepository<BusinessApplication, Guid> businessApplicationRepository,
            IRepository<WorkAuditor, Guid> workAuditorRepository,
            CodeFormatDescAppService codeFormatDescAppServiceRepository,
            IRepository<User, long> userRepository,
            IRepository<UserRole, long> userRoleRepository,
            IOperationHistoryAppService iOperationHistoryAppService,
            IRepository<ProductionScheduler, Guid> productionSchedulerRepository
            )
        {
            _techniqueEntityRepository = techniqueEntityRepository;
            _processesEntityRepository = processesEntityRepository;
            _workStepEntityRepository = workStepEntityRepository;
            _bopNodeRepository = bopNodeRepository;
            _bopDescRepository = bopDescRepository;
            _modifyManageRepository = modifyManageRepository;
            _tableBaseEntity = tableBaseEntity;
            _convertFormBaseEntity = convertFormBaseEntity;
            _processLineRepository = processLineRepository;
            _sysCodeRepository = sysCodeRepository;
            _processManage = processManage;
            _relationalCorrespondRepository = relationalCorrespondRepository;
            _loadPieceRepository = loadPieceRepository;
            _makeResourcesEntityRepository = makeResourcesEntityRepository;
            _videoEntityRepository = videoEntityRepository;
            _storeStockContentRepsitory = storeStockContentRepsitory;
            _workFlowAppService = workFlowAppService;
            _workFlowNodeRepository = workFlowNodeRepository;
            _businessApplicationRepository = businessApplicationRepository;
            _workAuditorRepository = workAuditorRepository;
            _codeFormatDescAppServiceRepository = codeFormatDescAppServiceRepository;
            _userRepository = userRepository;
            _userRoleRepository = userRoleRepository;
            _iOperationHistoryAppService = iOperationHistoryAppService;
            _productionSchedulerRepository = productionSchedulerRepository;
        }
        /// <summary>
        /// 根据发次、型号获取工艺规程
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        public PagedResultDto<MoadifTechniqueOutput> GetMoadifTechnique(SelectMoadifDto input)
        {
            if (input.ModelId==null || input.LotNoId == null)
            {
                throw new UserFriendlyException("请选择查询的型号与发次!");
            }
            var query = from temp1 in _bopNodeRepository.GetAll()
                        join temp2 in _bopDescRepository.GetAll() on temp1.BopDescId equals temp2.Id
                        join temp3 in _techniqueEntityRepository.GetAll() on temp1.TechniqueEntityId equals temp3.Id
                        where temp1.TechniqueEntityId != null  //  && temp1.IsExport == 0 && temp1.PlanExprot == false && temp1.BopExprot == false
                        select new
                        {
                            Id = temp3.Id,
                            TechniqueName = temp3.TechniqueName,
                            TechniqueNumber = temp3.TechniqueNumber,
                            ModuleCode = temp3.ModuleCode,
                            Edition = temp3.Edition,
                            Model = temp2.Model,
                            LotNo = temp2.LotNo,
                            ModelId = temp2.ModelId,
                            LotNoId = temp2.LotNoId,
                            ModelName = temp3.ModuleName,
                            DrawingNo = temp3.ProductCode,
                            StageSign = GetEnumDesc(temp3.StageSign),
                            IsExport = temp1.IsExport,
                            PlanExprot = temp1.PlanExprot,
                            BopExprot = temp1.BopExprot,
                        };
            var techList = query.WhereIf(input.ModelId != null, d => d.ModelId == input.ModelId)
                .WhereIf(input.LotNoId != null, d => d.LotNoId == input.LotNoId)
                .WhereIf(!string.IsNullOrEmpty(input.TechniqueName), d => d.TechniqueName.Contains(input.TechniqueName))
                .WhereIf(!string.IsNullOrEmpty(input.TechniqueNumber), d => d.TechniqueNumber.Contains(input.TechniqueNumber))
                .ToList();
            int count = techList.Count();
            List<MoadifTechniqueOutput> tempData = new List<MoadifTechniqueOutput>();
            var modifRes = _modifyManageRepository.GetAll().Where(d => d.DocumentStatus == DocumentStatus.审核中).Select(d => d.TechniqueId).ToList();
            for (int i = 0; i < techList.Count; i++)
            {
                MoadifTechniqueOutput moadif = new MoadifTechniqueOutput();
                moadif.Id = techList[i].Id;
                moadif.TechniqueName = techList[i].TechniqueName;
                moadif.TechniqueNumber = techList[i].TechniqueNumber;
                moadif.ModuleCode = techList[i].ModuleCode;
                moadif.Edition = techList[i].Edition;
                moadif.Model = techList[i].Model;
                moadif.LotNo = techList[i].LotNo;
                moadif.ModelId = techList[i].ModelId;
                moadif.LotNoId = techList[i].LotNoId;
                moadif.ModelName = techList[i].ModelName;
                moadif.DrawingNo = techList[i].DrawingNo;
                moadif.StageSign = techList[i].StageSign;
                moadif.techStatus = "未导出";
                if (techList[i].IsExport == 1)
                {
                    moadif.techStatus = "已导出";
                }
                if (techList[i].PlanExprot)
                {
                    moadif.techStatus = "计划导出";
                }
                if (techList[i].BopExprot)
                {
                    moadif.techStatus = "Bop导出";
                }

                if (modifRes.Count() > 0)
                {
                    if (modifRes.FindIndex(d => d == techList[i].Id) != -1)
                    {
                        moadif.techStatus = "变更审核中";
                    }
                }
                tempData.Add(moadif);
            }
            var result = tempData.AsQueryable().PageBy(input);
            return new PagedResultDto<MoadifTechniqueOutput>(count, result.ToList());
        }
        /// <summary>
        /// 获取更改业务相关列表
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        public PagedResultDto<ModifTechniqueDto> GetMoadifManage(SelectMoadifDto input)
        {
            var modifManageList = _modifyManageRepository.GetAll().WhereIf(!string.IsNullOrEmpty(input.Model), d => d.Model.Contains(input.Model))
               .WhereIf(!string.IsNullOrEmpty(input.LotNo), d => d.LotNo.Contains(input.LotNo))
               .WhereIf(!string.IsNullOrEmpty(input.DrawingNo), d => d.DrawingNo.Contains(input.DrawingNo))
               .WhereIf(!string.IsNullOrEmpty(input.ModifyType), d => d.ModifyType==input.ModifyType).ToList();
            int count = modifManageList.Count();
            var result = modifManageList.OrderByDescending(d => d.ApplicationDate).AsQueryable().PageBy(input.SkipCount, input.MaxResultCount);
            return new PagedResultDto<ModifTechniqueDto>(count, ObjectMapper.Map<List<ModifTechniqueDto>>(result));
        }
        /// <summary>
        /// 保存或者修改变更管理
        /// </summary>
        /// <param name="input"></param>
        public ResultMessage HoldMoadifManage(CreateModifManageInput input)
        {
            ResultMessage resultMessage = new ResultMessage();
            try
            {
                //保存变更业务
                if (input.CreateFlag == 0)
                {
                    var tempModif = _modifyManageRepository.GetAll().Where(d => d.TechniqueId == input.TechniqueId && (d.DocumentStatus == DocumentStatus.编制中 || d.DocumentStatus == DocumentStatus.审核中)).FirstOrDefault();
                    if (tempModif != null)
                    {
                        resultMessage.code = 1;
                        resultMessage.Message = "存有发起变更同一本工艺规程的业务！业务单号为：" + tempModif.ModifyNumber;
                        return resultMessage;
                        //throw new UserFriendlyException("存有发起变更同一本工艺规程的业务！业务单号为：" + tempModif.ModifyNumber);
                    }
                    ModifyManage modifyManage = new ModifyManage();
                    modifyManage = ObjectMapper.Map<ModifyManage>(input);
                    if (input.TechniqueId != null)
                    {
                        var tempData = (from cc in _techniqueEntityRepository.GetAll().Where(d => d.Id == input.TechniqueId)
                                        join mm in _bopNodeRepository.GetAll() on cc.Id equals mm.TechniqueEntityId
                                        join ee in _bopDescRepository.GetAll() on mm.BopDescId equals ee.Id
                                        select new
                                        {
                                            Loto = ee.LotNo,
                                            ModelId = ee.ModelId,
                                            LotNoId = ee.LotNoId,
                                            Model = ee.Model
                                        }).First();
                        modifyManage.LotNoId = tempData.LotNoId;
                        modifyManage.ModelId = tempData.ModelId;
                        modifyManage.LotNo = tempData.Loto;
                        modifyManage.Model = tempData.Model;

                    }
                    else
                    {
                        resultMessage.code = 1;
                        resultMessage.Message = "请选择工艺规程！";
                        return resultMessage;
                    }
                    var modifyNumber = _codeFormatDescAppServiceRepository.GetCodeFormat("工艺规程变更");
                    if (modifyNumber == null)
                    {
                        modifyManage.ModifyNumber = _codeFormatDescAppServiceRepository.GetOrderCode("BGGL", "yyyyMMdd", 1, 5, 1);
                    }
                    else
                    {
                        modifyManage.ModifyNumber = modifyNumber;
                    }
                    //modifyManage.ModifyNumber = _codeFormatDescAppServiceRepository.GetOrderCode("MM", "yyyyMMdd", 1, 5, 1);
                    modifyManage.DocumentStatus = DocumentStatus.编制中;
                    modifyManage.UserId = GetCurrentUser().Id;
                    modifyManage.UserName = GetCurrentUser().Surname + GetCurrentUser().Name;
                    modifyManage.ApplicationDate = DateTime.Now;
                    var tempRe = _relationalCorrespondRepository.FirstOrDefault(d => d.FormerId == input.TechniqueId && d.RelationalType == 1);
                    if (tempRe != null)
                    {
                        modifyManage.DestinationTechniqueId = tempRe.GoalId;
                        modifyManage.LastEdition = _techniqueEntityRepository.Get(tempRe.GoalId).Edition;
                    }
                    else
                    {
                        resultMessage.code = 1;
                        resultMessage.Message = "请先编辑要变更的工艺规程然后再发起该业务！";
                        return resultMessage;
                        //throw new UserFriendlyException("请先编辑要变更的工艺规程然后再发起该业务！");
                    }
                    var modifId = _modifyManageRepository.InsertAndGetId(modifyManage);
                    _iOperationHistoryAppService.InsertOperationLogNew(modifId, OperationHistory.BusinessTypes.Bop变更管理, OperationHistory.OperationTypes.新增Bop变更, GetCurrentUser().Surname + GetCurrentUser().Name + "于" + DateTime.Now.ToString() + "创建Bop变更业务");
                }
                else
                {
                    //修改变更业务
                    var temp = _modifyManageRepository.GetAll().Where(d => d.Id == input.Id).FirstOrDefault();
                    if (temp != null)
                    {
                        if (temp.DocumentStatus == DocumentStatus.审核中 || temp.DocumentStatus == DocumentStatus.已发布)
                        {
                            resultMessage.code = 1;
                            resultMessage.Message = "该单据正在审核或者已经发布不可重复发起该业务！";
                            return resultMessage;
                            //throw new UserFriendlyException("该单据正在审核或者已经发布不可重复发起该业务！");
                        }
                        var modifyNumber = _codeFormatDescAppServiceRepository.GetCodeFormat("变更管理");
                        if (modifyNumber == null)
                        {
                            temp.ModifyNumber = _codeFormatDescAppServiceRepository.GetOrderCode("BGGL", "yyyyMMdd", 1, 5, 1); 
                        }
                        else
                        {
                            temp.ModifyNumber = modifyNumber;
                        }
                        //temp.ModifyNumber = _codeFormatDescAppServiceRepository.GetOrderCode("MM", "yyyyMMdd", 1, 5, 1);
                     
                        temp.ModifyType = input.ModifyType;
                        temp.ModifyReason = input.ModifyReason;
                        //temp.TechniqueName = input.TechniqueName;
                        //temp.TechniqueNumber = input.TechniqueNumber;
                        temp.ProductOpinions = input.ProductOpinions;
                        temp.Content = input.Content;
                        temp.Remark = input.Remark;
                        //temp.ModelName = input.ModelName;
                        //temp.ModuleCode = input.ModuleCode;
                        //temp.DrawingNo = input.DrawingNo;
                        //temp.StageSign = input.StageSign;
                        //temp.ReEdition = input.ReEdition;
                        //temp.LastEdition = input.LastEdition;
                        //temp.TechniqueId = input.TechniqueId.Value;
                        // temp.DestinationTechniqueId = input.DestinationTechniqueId.Value;
                        var tempRe = _relationalCorrespondRepository.FirstOrDefault(d => d.FormerId == input.TechniqueId && d.RelationalType == 1);
                        if (tempRe != null)
                        {
                            temp.DestinationTechniqueId = tempRe.GoalId;
                            temp.LastEdition = _techniqueEntityRepository.Get(tempRe.GoalId).Edition;
                        }
                        else
                        {
                            resultMessage.code = 1;
                            resultMessage.Message = "请先编辑要变更的工艺规程然后再修改该业务！";
                            return resultMessage;
                            //throw new UserFriendlyException("请先编辑要变更的工艺规程然后再修改该业务！");
                        }
                        _modifyManageRepository.Update(temp);
                        _iOperationHistoryAppService.InsertOperationLogNew(input.Id.Value, OperationHistory.BusinessTypes.Bop变更管理, OperationHistory.OperationTypes.修改, GetCurrentUser().Surname + GetCurrentUser().Name + "于" + DateTime.Now.ToString() + "修改Bop变更业务信息");
                    }
                }
                resultMessage.code = 0;
                return resultMessage;
            }
            catch (Exception ex)
            {
                resultMessage.code = 1;
                resultMessage.Message = ex.Message;
                return resultMessage;
            }
        }
        /// <summary>
        /// 保存送审
        /// </summary>
        public ResultMessage PushMoadifManage(BusinessApplicationModifInput input)
        {
            ResultMessage resultMessage = new ResultMessage();
            try
            { 
                //新增发送变更业务
                if (input.ModifyManage.CreateFlag == 0)
                {
                    //先获取 业务 然后校验是否已发送相同的规程 最后 推送审批流 修改状态
                    var tempModif = _modifyManageRepository.GetAll().Where(d => d.TechniqueId == input.ModifyManage.TechniqueId && (d.DocumentStatus == DocumentStatus.编制中 || d.DocumentStatus == DocumentStatus.审核中)).FirstOrDefault();
                    if (tempModif != null)
                    {
                        resultMessage.code = 1;
                        resultMessage.Message = "存有发起变更同一本工艺规程的业务！业务单号为：" + tempModif.ModifyNumber;
                        return resultMessage;
                        //throw new UserFriendlyException("存有发起变更同一本工艺规程的业务！业务单号为：" + tempModif.ModifyNumber);
                    }
                    string businessDesc = "";
                    if (input.ModifyManage.TechniqueId != null)
                    {
                        var fTemp = (from tempTech in _techniqueEntityRepository.GetAll()
                                     join tempNode in _bopNodeRepository.GetAll() on tempTech.Id equals tempNode.TechniqueEntityId
                                     join tempDesc in _bopDescRepository.GetAll() on tempNode.BopDescId equals tempDesc.Id
                                     where tempTech.Id == input.ModifyManage.TechniqueId
                                     select new
                                     {
                                         Model = tempDesc.Model,
                                         LotNo = tempDesc.LotNo,
                                         TechniqueNumber = tempTech.TechniqueNumber,
                                         Edition = tempTech.Edition
                                     }).ToList();
                        if (fTemp.Count > 0)
                        {
                            var oneTemp = fTemp.First();
                            businessDesc = "型号:" + oneTemp.Model + ",发次:" + oneTemp.LotNo + ",工艺规程编号:" + oneTemp.TechniqueNumber + ",原版本号:" + oneTemp.Edition;
                        }
                    }
                    ModifyManage modifyManage = new ModifyManage();
                    modifyManage = ObjectMapper.Map<ModifyManage>(input.ModifyManage);
                    var modifyNumber = _codeFormatDescAppServiceRepository.GetCodeFormat("变更管理");
                    if (modifyNumber == null)
                    {
                        modifyManage.ModifyNumber = _codeFormatDescAppServiceRepository.GetOrderCode("BGGL", "yyyyMMdd", 1, 5, 1);
                    }
                    else
                    {
                        modifyManage.ModifyNumber = modifyNumber;
                    }
                    //推送审批流
                    PushBusInput push = new PushBusInput();
                    push.WorkAuditorList = input.WorkAuditorList;
                    push.Type = input.Type; //发起审核默认  变更工艺规程流程为0
                    push.FunModule = "变更管理";
                    push.Menu = "规程变更管理";
                    push.BusinessDesc = businessDesc;
                    push.BusinessNumber = modifyManage.ModifyNumber;
                    Guid busId = _workFlowAppService.PushBusinessApplication(push);

                 
                    //modifyManage.ModifyNumber = _codeFormatDescAppServiceRepository.GetOrderCode("BG", "yyyyMMdd", 1, 5, 1);
                    modifyManage.DocumentStatus = DocumentStatus.审核中;
                    modifyManage.UserId = GetCurrentUser().Id;
                    modifyManage.UserName = GetCurrentUser().Surname + GetCurrentUser().Name;
                    modifyManage.ApplicationDate = DateTime.Now;
                    var tempRe = _relationalCorrespondRepository.FirstOrDefault(d => d.FormerId == input.ModifyManage.TechniqueId && d.RelationalType == 1);
                    if (tempRe != null)
                    {
                        modifyManage.DestinationTechniqueId = tempRe.GoalId;
                        modifyManage.LastEdition = _techniqueEntityRepository.Get(tempRe.GoalId).Edition;
                    }
                    else
                    {
                        resultMessage.code = 1;
                        resultMessage.Message = "请先编辑要变更的工艺规程然后再修改该业务！";
                        return resultMessage;
                        //throw new UserFriendlyException("请先编辑要变更的工艺规程然后再发起该业务！");
                    }
                    modifyManage.BusinessId = busId;
                    var modifId = _modifyManageRepository.InsertAndGetId(modifyManage);
                    _iOperationHistoryAppService.InsertOperationLogNew(modifId, OperationHistory.BusinessTypes.Bop变更管理, OperationHistory.OperationTypes.新增Bop变更, GetCurrentUser().Surname + GetCurrentUser().Name + "于" + DateTime.Now.ToString() + "新增Bop变更并送审。");
                }
                else
                {
                    //修改业务信息后 推送审批流
                    var temp = _modifyManageRepository.GetAll().Where(d => d.Id == input.ModifyManage.Id).FirstOrDefault();
                    if (temp != null)
                    {
                        //被驳回后重新发送审批
                        if (temp.DocumentStatus == DocumentStatus.被驳回)
                        {
                            RejectPushBusInput reject = new RejectPushBusInput();
                            reject.WorkAuditorList = input.WorkAuditorList;
                            reject.Type = input.Type;
                            reject.Id = temp.BusinessId.Value;
                            _workFlowAppService.RejectPushBusinessApplication(reject);

                        }
                        else
                        {
                            string businessDesc = "";
                            if (input.ModifyManage.TechniqueId != null)
                            {
                                var fTemp = (from tempTech in _techniqueEntityRepository.GetAll()
                                             join tempNode in _bopNodeRepository.GetAll() on tempTech.Id equals tempNode.TechniqueEntityId
                                             join tempDesc in _bopDescRepository.GetAll() on tempNode.BopDescId equals tempDesc.Id
                                             where tempTech.Id == input.ModifyManage.TechniqueId
                                             select new
                                             {
                                                 Model = tempDesc.Model,
                                                 LotNo = tempDesc.LotNo,
                                                 TechniqueNumber = tempTech.TechniqueNumber,
                                                 Edition = tempTech.Edition
                                             }).ToList();
                                if (fTemp.Count > 0)
                                {
                                    var oneTemp = fTemp.First();
                                    businessDesc = oneTemp.Model + oneTemp.LotNo + oneTemp.TechniqueNumber + oneTemp.Edition;
                                }
                            }
                            PushBusInput push = new PushBusInput();
                            push.WorkAuditorList = input.WorkAuditorList;
                            push.Type = input.Type;
                            push.FunModule = "变更管理";
                            push.Menu = "规程变更管理";
                            push.BusinessDesc = businessDesc;
                            push.BusinessNumber = input.ModifyManage.ModifyNumber;
                            Guid busId = _workFlowAppService.PushBusinessApplication(push);
                            temp.BusinessId = busId;
                        }
                        temp.DocumentStatus = DocumentStatus.审核中;
                        temp.Model = input.ModifyManage.Model;
                        temp.LotNo = input.ModifyManage.LotNo;
                        temp.ModelId = input.ModifyManage.ModelId;
                        temp.LotNoId = input.ModifyManage.LotNoId;
                        temp.ModifyType = input.ModifyManage.ModifyType;
                        temp.ModifyReason = input.ModifyManage.ModifyReason;
                        temp.TechniqueName = input.ModifyManage.TechniqueName;
                        temp.TechniqueNumber = input.ModifyManage.TechniqueNumber;
                        temp.ProductOpinions = input.ModifyManage.ProductOpinions;
                        temp.Content = input.ModifyManage.Content;
                        temp.Remark = input.ModifyManage.Remark;
                        temp.ModelName = input.ModifyManage.ModelName;
                        temp.ModuleCode = input.ModifyManage.ModuleCode;
                        temp.DrawingNo = input.ModifyManage.DrawingNo;
                        temp.StageSign = input.ModifyManage.StageSign;
                        temp.ReEdition = input.ModifyManage.ReEdition;
                        temp.TechniqueId = input.ModifyManage.TechniqueId.Value;
                        // temp.DestinationTechniqueId = input.DestinationTechniqueId.Value;
                        var tempRe = _relationalCorrespondRepository.FirstOrDefault(d => d.FormerId == input.ModifyManage.TechniqueId && d.RelationalType == 1);
                        if (tempRe != null)
                        {
                            temp.DestinationTechniqueId = tempRe.GoalId;
                            temp.LastEdition = _techniqueEntityRepository.Get(tempRe.GoalId).Edition;
                        }
                        else
                        {
                            resultMessage.code = 1;
                            resultMessage.Message = "请先编辑要变更的工艺规程然后再修改该业务！";
                            return resultMessage;
                            //throw new UserFriendlyException("请先编辑要变更的工艺规程然后再修改该业务！");
                        }
                        _modifyManageRepository.Update(temp);
                        _iOperationHistoryAppService.InsertOperationLogNew(input.ModifyManage.Id.Value, OperationHistory.BusinessTypes.Bop变更管理, OperationHistory.OperationTypes.修改, GetCurrentUser().Surname + GetCurrentUser().Name + "于" + DateTime.Now.ToString() + "修改Bop变更信息并送审。");
                    }
                }
                resultMessage.code = 0;
                return resultMessage;
            }
            catch (Exception ex)
            {
                resultMessage.code = 1;
                resultMessage.Message = ex.Message;
                return resultMessage;
            }
        }

        /// <summary>
        /// 根据业务Id查询变更管理业务详情
        /// </summary>
        /// <param name="bappId"></param>
        /// <returns></returns>
        public ModifResult DisplayBusinessById(Guid bappId)
        {
            ModifResult result = new ModifResult();
            var modif = _modifyManageRepository.FirstOrDefault(d => d.BusinessId == bappId);
            if (modif != null)
            {
                var business = _businessApplicationRepository.Get(bappId);
                var workNode = _workFlowNodeRepository.GetAll().First(d => d.WnID == business.BAppType && d.WfID == business.Status);
                var workAuditorList = _workAuditorRepository.GetAll().Where(d => d.BappId == bappId);

                var currentUser = GetCurrentUser();
                var currentRoles = _userRoleRepository.GetAll().Where(userRole => userRole.UserId == currentUser.Id).Select(userRole => userRole.RoleId).ToArray();
                //先获取审批节点
                if (workNode.NextNode == "0")
                {//业务结束只能查看
                    result.DisplayApproval = false;
                }
                else if ((currentUser.Id == business.ExamineUserId)/*|| (currentUser.Roles.Select(d => d.RoleId).Contains(Convert.ToInt32(workNode.Handlers)) && currentUser.Id != business.UserID)*/)
                {//处理用户业务的节点
                    result.DisplayApproval = true;
                }
                else if (currentRoles.Length > 0)
                {
                    string[] bigArr = Array.ConvertAll(currentRoles, _ => _.ToString());

                    var smallArr = workNode.Handlers.Split(',').ToArray();
                    var exceptArr = bigArr.Intersect(smallArr);
                    if (exceptArr.Any())
                    {
                        if (business.ExamineUserId == null)
                        {
                            result.DisplayApproval = true;
                        }
                    }

                }
                else
                {//非本人处理，只是查看
                    result.DisplayApproval = false;
                }
                var users = _userRepository.GetAll().ToList();
                result.ModifTechnique = ObjectMapper.Map<ModifTechniqueDto>(modif);
                result.WorkAuditorList = (from tempQy in workAuditorList
                                          join wf in _workFlowNodeRepository.GetAll() on tempQy.WfID equals wf.WfID
                                          join user in users on tempQy.UserId equals user.Id
                                          where wf.WnID == tempQy.WnID
                                          select new WorkAuditorOutput
                                          {
                                              BappId = tempQy.BappId,
                                              WfName = wf.WnName,
                                              UserName = user.Surname + user.Name,
                                              Result = tempQy.Result,
                                              Remark = tempQy.Remark,
                                              AuditTime = tempQy.AuditTime
                                          }).ToList();
            }
            return result;
        }

        /// <summary>
        /// 根据Id获取变更申请信息
        /// </summary>
        /// <param name="guid"></param>
        /// <returns></returns>
        public ModifTechniqueDto GetMoadifManageById(Guid guid)
        {
            var temp = _modifyManageRepository.Get(guid);
            return ObjectMapper.Map<ModifTechniqueDto>(temp);
        }
        /// <summary>
        /// 变更管理根据Id获取工艺规程信息
        /// </summary>
        /// <param name="Id"></param>
        /// <returns></returns>
        public async Task<BopContentInfoDto> GetMoadifManageInfoById(Guid Id)
        {
            var bopContentInfo = new BopContentInfoDto();
            var tech = _techniqueEntityRepository.FirstOrDefault(x => x.Id == Id);
            var tempRe = _relationalCorrespondRepository.FirstOrDefault(d => d.GoalId == tech.Id && d.RelationalType == 1);
            if (tempRe != null)
            {
                var bopNode = _bopNodeRepository.FirstOrDefault(x => x.TechniqueEntityId == tempRe.FormerId);
                if (bopNode == null)
                {
                    if (tech != null)
                    {
                        bopContentInfo.ProcessName = tech.TechniqueName;
                        bopContentInfo.NodeStageSign = tech.StageSign;
                        bopContentInfo.NodeStageSignDesc = ((StageSigns)tech.StageSign).ToString();
                        string url = ConfigHelper.GetAppSetting("App", "GetAppUrl");
                        bopContentInfo.TechniqueExplain = tech.TechniqueExplain.Replace("../", url + @"/");
                    }
                    return bopContentInfo;
                }
                var bop = await _bopNodeRepository.GetAll().Include(c => c.BopContents).FirstOrDefaultAsync(p => p.Id == bopNode.Id);
                if (bop != null)
                {
                    if (bop != null)
                    {
                        bopContentInfo.NodeDrawingNo = bop.NodeDrawingNo;
                        bopContentInfo.NodeName = bop.NodeName;
                        if (bop.BopContents != null)
                        {
                            bopContentInfo.ContentId = bop.BopContents.Id;
                            bopContentInfo.Remark = bop.BopContents.Remark;
                        }
                    }
                    if (tech != null)
                    {
                        bopContentInfo.ProcessCode = bop.ProcessCode;
                        bopContentInfo.ProcessName = tech.TechniqueName;
                        bopContentInfo.NodeStageSign = tech.StageSign;
                        bopContentInfo.NodeStageSignDesc = ((StageSigns)tech.StageSign).ToString();
                        bopContentInfo.PadName = bop.PadName;
                        bopContentInfo.ExportDate = bop.ExportDate;
                        bopContentInfo.RelationDate = bop.RelationDate;
                        bopContentInfo.TechniqueExplain = tech.TechniqueExplain;
                    }
                }

            }

            return bopContentInfo;
        }

        #region 修改节点信息
        /// <summary>
        /// 修改卡片文本内容
        /// </summary>
        /// <param name="input"></param>
        public ResultMessage DefendTechniqueExplain(TechContentInput input)
        {
            ResultMessage resultMessage = new ResultMessage();
            try
            {
                var techTemp = _techniqueEntityRepository.FirstOrDefault(d => d.Id == input.TechId);
                if (techTemp != null)
                {
                    string url = ConfigHelper.GetAppSetting("App", "GetAppUrl");
                    techTemp.TechniqueExplain = input.TechniqueExplain.Replace(url + @"/", "../");
                    _techniqueEntityRepository.Update(techTemp);
                }
                else
                {
                    resultMessage.code = 1;
                    resultMessage.Message = "修改工艺说明卡片失败！失败原因: 未找到相关工艺规程！";
                    return resultMessage;
                    //throw new UserFriendlyException("修改工艺说明卡片失败！失败原因:未找到相关工艺规程！");
                }
                resultMessage.code = 0;
                return resultMessage;
            }
            catch (Exception ex)
            {
                resultMessage.code = 1;
                resultMessage.Message = ex.Message;
                return resultMessage;
            }
        }
        /// <summary>
        /// 修改部套描述
        /// </summary>
        /// <param name="input"></param>
        public ResultMessage DefendTechniqueNode(TechContentInput input)
        {
            ResultMessage resultMessage = new ResultMessage();
            try
            {
                var nodeTemp = _bopNodeRepository.GetAll().Where(d => d.TechniqueEntityId == input.TechId).FirstOrDefault();
                if (nodeTemp != null)
                {
                    nodeTemp.NodeDrawingNo = input.NodeDrawingNo;
                    nodeTemp.NodeName = input.NodeName;
                    _bopNodeRepository.Update(nodeTemp);
                    resultMessage.code = 0;
                    return resultMessage;
                }
                else
                {
                    resultMessage.code = 1;
                    resultMessage.Message = "修改部套描述失败！失败原因:未找到相关节点！";
                    return resultMessage;
                }
            }
            catch (Exception ex)
            {
                resultMessage.code = 1;
                resultMessage.Message = ex.Message;
                return resultMessage;
            }
        }
        /// <summary>
        /// 修改工艺规程
        /// </summary>
        /// <param name="input"></param>
        public ResultMessage DefendTechnique(TechDefendInput input)
        {
            ResultMessage resultMessage = new ResultMessage();
            try
            {
                var techTemp = _techniqueEntityRepository.FirstOrDefault(d => d.Id == input.Id);
                if (techTemp != null)
                {
                    techTemp.TechniqueName = input.TechniqueName;
                    techTemp.TechniqueNumber = input.TechniqueNumber;
                    techTemp.SystemCode = input.SystemCode;
                    techTemp.ProductCode = input.ProductCode;
                    techTemp.ModuleCode = input.ModuleCode;
                    techTemp.ModuleName = input.ModuleName;
                    techTemp.StageSign = input.StageSign.Value;
                    techTemp.TechniqueType = input.TechniqueType.Value;
                    techTemp.TechniqueCharacter = input.TechniqueCharacter;
                    techTemp.Shape = input.Shape.Value;
                    techTemp.SecretDegree = input.SecretDegree.Value;
                    techTemp.UseUnit = input.UseUnit;
                    techTemp.UseTime = input.UseTime;
                    techTemp.BasisFile = input.BasisFile;
                    techTemp.IssueUnit = input.IssueUnit;
                    techTemp.Remark = input.Remark;
                    _techniqueEntityRepository.Update(techTemp);
                }
                else
                {
                    resultMessage.code = 1;
                    resultMessage.Message = "修改工艺规程信息失败！失败原因:未找到相关工艺规程！";
                    return resultMessage;
                    //throw new UserFriendlyException("修改工艺规程信息失败！失败原因:未找到相关工艺规程！");
                }
                resultMessage.code = 0;
                return resultMessage;
            }
            catch (Exception ex)
            {
                resultMessage.code = 1;
                resultMessage.Message = ex.Message;
                return resultMessage;
            }
        }

        /// <summary>
        /// 删除变更业务
        /// </summary>
        /// <param name="Id"></param>
        public ResultMessage DeleteModif(Guid Id)
        {
            ResultMessage resultMessage = new ResultMessage();
            try
            {
                var modify = _modifyManageRepository.Get(Id);
                if (modify.DocumentStatus == DocumentStatus.审核中 || modify.DocumentStatus == DocumentStatus.已发布)
                {
                    resultMessage.code = 1;
                    resultMessage.Message = "该单据正在审核或者已经发布不可删除！";
                    return resultMessage;
                }
                else
                {
                    _modifyManageRepository.Delete(Id);
                }
                resultMessage.code = 0;
                return resultMessage;
            }
            catch (Exception ex)
            {
                resultMessage.code = 1;
                resultMessage.Message = ex.Message;
                return resultMessage;
            }
        }
        #endregion


        /// <summary>
        /// 审批变更管理
        /// </summary>
        /// <param name="input"></param>
        public void ApproveModif(ApproveInput input)
        {
            int status = 0;
            _workFlowAppService.SendToFlow(input.BappId, input.Operation, input.Remark, out status);
            //审批流推送结果
            if (status == 99)
            {
                //成功 先获取 业务信息
                var modif = _modifyManageRepository.GetAll().Where(d => d.BusinessId == input.BappId).FirstOrDefault();
                modif.DocumentStatus = DocumentStatus.已发布;
                _modifyManageRepository.Update(modif);
                _iOperationHistoryAppService.InsertOperationLogNew(modif.Id, OperationHistory.BusinessTypes.Bop变更管理, OperationHistory.OperationTypes.审批结束, "于" + DateTime.Now.ToString() + "审批成功。");
                var bopNode = _bopNodeRepository.FirstOrDefault(d => d.TechniqueEntityId == modif.TechniqueId);
                if (bopNode != null)
                {
                    bopNode.TechniqueEntityId = modif.DestinationTechniqueId;
                    _bopNodeRepository.Update(bopNode);
                    //更新路线信息
                    var proLineago = _processLineRepository.GetAll().Where(d => d.PPtr == bopNode.Id);
                    foreach (var item in proLineago)
                    {
                        item.PPtr = modif.TechniqueId;
                        item.BopDescId = null;
                        _processLineRepository.Update(item);
                    }
                    var proLine = _processLineRepository.GetAll().Where(d => d.PPtr == modif.DestinationTechniqueId);
                    foreach (var item in proLine)
                    {
                        item.PPtr = bopNode.Id;
                        item.BopDescId = bopNode.BopDescId;
                        _processLineRepository.Update(item);
                    }
                   
                }
                //更新规程信息
                var technew = _techniqueEntityRepository.FirstOrDefault(d => d.Id == modif.DestinationTechniqueId);
                if (technew != null)
                {
                    if (bopNode != null)
                    {
                        technew.FileStatus = FileStatus.已发布;
                    }
                    else
                    {
                        technew.FileStatus = FileStatus.新增;
                    }
                    _techniqueEntityRepository.Update(technew);
                }
                var techold = _techniqueEntityRepository.FirstOrDefault(d => d.Id == modif.TechniqueId);
                if (techold != null)
                {
                    techold.FileStatus = FileStatus.历史版本;
                    _techniqueEntityRepository.Update(techold);
                    var tempSchs = _productionSchedulerRepository.GetAll().Where(d => d.ParentId == bopNode.Id).ToList();
                    foreach (var item in tempSchs)
                    {
                        _productionSchedulerRepository.Delete(item);
                    }
                    //更新调度任务信息
                    var proSchs = _processesEntityRepository.GetAll().Where(d => d.TechniqueEntityId == modif.TechniqueId).Select(d => d.Id).ToList();
                    if (proSchs.Count > 0)
                    {
                        _productionSchedulerRepository.Delete(d => proSchs.Contains(d.ParentId));
                    }
                    var workRelation = (from cc in _loadPieceRepository.GetAll()
                                        join mm in _workStepEntityRepository.GetAll() on cc.WorkStepEntityId equals mm.Id
                                        join ee in _relationalCorrespondRepository.GetAll() on cc.Id equals ee.FormerId
                                        select new
                                        {
                                            FormId = ee.FormerId,
                                            GoalId = ee.GoalId,

                                        }).ToList();
                    //更新装入件明细id
                    if (workRelation.Count > 0)
                    {
                        var stcok = (from cc in _storeStockContentRepsitory.GetAll()
                                     join mm in workRelation on cc.LoadDetailsId equals mm.FormId
                                     select cc).ToList();
                        if (stcok.Count > 0)
                        {
                            foreach (var item in stcok)
                            {
                                item.LoadDetailsId = workRelation.First(d => d.FormId == item.LoadDetailsId).GoalId;
                                _storeStockContentRepsitory.Update(item);
                            }
                        }
                    }
                    _iOperationHistoryAppService.InsertOperationLogNew(technew.Id, OperationHistory.BusinessTypes.Bop变更管理, OperationHistory.OperationTypes.默认修改, "【默认修改】" + "由原版本" + techold.Edition + "变更到" + technew.Edition + "子版本");

                }

            }
            if (status == 100)
            {
                var modif = _modifyManageRepository.GetAll().Where(d => d.BusinessId == input.BappId).FirstOrDefault();
                modif.DocumentStatus = DocumentStatus.被驳回;
                _modifyManageRepository.Update(modif);
                _iOperationHistoryAppService.InsertOperationLogNew(modif.Id, OperationHistory.BusinessTypes.Bop变更管理, OperationHistory.OperationTypes.审批结束, "于" + DateTime.Now.ToString() + "审批失败。");
            }
        }

        /// <summary>
        /// 加载新型树结构
        /// </summary>
        /// <param name="sourceId"></param>
        /// <returns></returns>
        public TreeClass SpanningTechTree(Guid sourceId)
        {
            //复制规程数据 工序 工步 关联表 路线 然后 展示
            // 先判断是否已存在 新建的树 如果有 版本加1 则直接展示  如果没有 先 生成 后展示
            bool LoadNewTree = false;
            var tech = _techniqueEntityRepository.FirstOrDefault(d => d.Id == sourceId);
            if (tech != null)
            {
                string[] editionList;
                string edition = "";
                if (!string.IsNullOrEmpty(tech.Edition))
                {
                    //版本号小版本加一
                    editionList = tech.Edition.Split('-');
                    edition = editionList[0] + "-" + (int.Parse(editionList[1]) + 1).ToString().PadLeft(3, '0');
                }
                else
                {
                    var bopNode = _bopNodeRepository.FirstOrDefault(d => d.TechniqueEntityId == tech.Id);
                    if (bopNode != null)
                    {
                        var bopDesc = _bopDescRepository.Get(bopNode.BopDescId);
                        edition = bopDesc.LotNo + "-" + "001";
                    }
                }
                var newTech = _techniqueEntityRepository.FirstOrDefault(d => d.TechniqueNumber == tech.TechniqueNumber && d.TechniqueName == tech.TechniqueName & d.ModuleCode == tech.ModuleCode && d.Edition == edition.ToString());
                if (newTech != null)
                {
                    LoadNewTree = false;
                    var tempRe = _relationalCorrespondRepository.FirstOrDefault(d => d.FormerId == sourceId && d.RelationalType == 1);
                    if (tempRe != null)
                    {
                        tempRe.GoalId = newTech.Id;
                        tempRe.RelationalType = 1;
                        _relationalCorrespondRepository.Update(tempRe);
                    }
                    else
                    {
                        RelationalCorrespond relational = new RelationalCorrespond();
                        relational.FormerId = sourceId;
                        relational.GoalId = newTech.Id;
                        relational.RelationalType = 1;
                        _relationalCorrespondRepository.Insert(relational);
                    }
                }
                else
                {
                    LoadNewTree = true;
                }
                if (LoadNewTree)
                {

                    Dictionary<Guid, Guid> dicMap = new Dictionary<Guid, Guid>();
                    tech.Id = Guid.NewGuid();
                    tech.Edition = edition.ToString();
                    tech.ProcessesEntities = null;
                    tech.FileStatus = FileStatus.变更中;
                    //提取数据转换新树
                    _techniqueEntityRepository.Insert(tech);
                    Guid newTechId = new Guid(tech.Id.ToString());

                    TreeClass tree = new TreeClass();
                    tree.Id = new Guid(newTechId.ToString());
                    tree.ParentId = Guid.Empty;
                    tree.NodeDrawingNo = tech.TechniqueNumber;
                    tree.NodeName = tech.TechniqueName;
                    tree.NodeLevel = 0;
                    tree.Edition = edition.ToString();
                    var newProcessesList = _processesEntityRepository.GetAllIncluding(p => p.WorkStepEntities).Where(p => p.TechniqueEntityId == sourceId).OrderBy(n => n.ProcessesSequence);
                    foreach (var item in newProcessesList)
                    {
                        item.TechniqueEntityId = tech.Id;
                        var guid = Guid.NewGuid();
                        dicMap.Add(item.Id, guid);
                        item.Id = guid;
                        _processesEntityRepository.Insert(item);
                        TreeClass treeProcessNode = new TreeClass();
                        treeProcessNode.Id = item.Id;
                        treeProcessNode.ParentId = newTechId;
                        treeProcessNode.NodeDrawingNo = "工序" + item.ProcessesSequence.ToString() + " ";
                        treeProcessNode.NodeName = item.ProcessesName;
                        treeProcessNode.NodeLevel = 8;

                        item.WorkStepEntities = item.WorkStepEntities.OrderBy(r => r.WorkStepNumber).ToList();
                        foreach (var temp in item.WorkStepEntities)
                        {
                            var workGuid = Guid.NewGuid();
                            dicMap.Add(temp.Id, workGuid);
                            temp.Id = workGuid;
                            temp.ProcessesEntityId = item.Id;
                            temp.TechniqueEntityId = tech.Id;
                            _workStepEntityRepository.Insert(temp);

                            TreeClass wtree = new TreeClass();
                            wtree.Id = temp.Id;
                            wtree.ParentId = item.Id;
                            wtree.NodeDrawingNo = "工步" + item.ProcessesSequence.ToString();// + "-"+ witem.WorkStepNumber.ToString();
                            wtree.NodeName = temp.WorkStepNumber.ToString();//witem.WorkStepName  这个值数据库有问题
                            wtree.NodeLevel = 9;
                            treeProcessNode.children.Add(wtree);
                        }

                        tree.children.Add(treeProcessNode);
                    }
                    var workList = _workStepEntityRepository.GetAll().Where(d => d.TechniqueEntityId == sourceId).Select(d => d.Id);
                    #region 实体表
                    var loadPieceList = _loadPieceRepository.GetAll().Where(d => workList.Contains(d.WorkStepEntityId));
                    if (loadPieceList.Count() > 0)
                    {
                        var loadIdArray = loadPieceList.Select(d => d.Id).ToList();
                        var tempCorrespond = _relationalCorrespondRepository.GetAll().Where(d => loadIdArray.Contains(d.FormerId));
                        foreach (var item in tempCorrespond)
                        {
                            _relationalCorrespondRepository.Delete(item);
                        }
                    }
                    foreach (var item in loadPieceList)
                    {
                        var tempId = item.Id;
                        item.Id = Guid.NewGuid();
                        item.WorkStepEntityId = dicMap[item.WorkStepEntityId];
                        _loadPieceRepository.Insert(item);
                        RelationalCorrespond relational = new RelationalCorrespond();
                        relational.FormerId = tempId;
                        relational.GoalId = item.Id;
                        relational.RelationalType = 0;
                        _relationalCorrespondRepository.Insert(relational);
                    }
                    var makeResourcesEntityList = _makeResourcesEntityRepository.GetAll().Where(d => workList.Contains(d.WorkStepEntityId));
                    foreach (var item in makeResourcesEntityList)
                    {
                        item.Id = Guid.NewGuid();
                        item.WorkStepEntityId = dicMap[item.WorkStepEntityId];
                        _makeResourcesEntityRepository.Insert(item);
                    }
                    var videoEntityEntityList = _videoEntityRepository.GetAll().Where(d => workList.Contains(d.WorkStepEntityId));
                    foreach (var item in videoEntityEntityList)
                    {
                        item.Id = Guid.NewGuid();
                        item.WorkStepEntityId = dicMap[item.WorkStepEntityId];
                        _videoEntityRepository.Insert(item);
                    }
                    #endregion
                    #region 动态表
                    var tableData = _tableBaseEntity.GetAllIncluding(a => a.RecordRequirements, b => b.InspectionSignature, c => c.MeasuredResult, d => d.Environment, e => e.MultiMedia).Where(d => workList.Contains(d.WorkStepEntityId));
                    foreach (var item in tableData)
                    {
                        ConvertFormBase cFormbase = new ConvertFormBase(Guid.NewGuid(), item.FormName, item.SerialNum, dicMap[item.WorkStepEntityId], dicMap[item.ProcessesEntityId], item.Sort, item.Deptment,
                        item.ParentProductNum, item.ParentProductNum_DisplayName,
                        item.ParentProductNum_Enable, item.ParentProductNum_Show, item.ParentProductNum_Property, item.ParentProductName, item.ParentProductName_DisplayName, item.ParentProductName_Enable, item.ParentProductName_Show,
                        item.ParentProductName_Property, item.FisrtDrawingNum, item.FisrtDrawingNum_DisplayName, item.FisrtDrawingNum_Enable, item.FisrtDrawingNum_Show, item.FisrtDrawingNum_Property,
                        item.FirstDrawingName, item.FirstDrawingName_DisplayName, item.FirstDrawingName_Enable, item.FirstDrawingName_Show, item.FirstDrawingName_Property,
                        item.SecondDrawingNum, item.SecondDrawingNum_DisplayName, item.SecondDrawingNum_Enable, item.SecondDrawingNum_Show, item.SecondDrawingNum_Property,
                        item.SecondDrawingName, item.SecondDrawingName_DisplayName, item.SecondDrawingName_Enable, item.SecondDrawingName_Show, item.SecondDrawingName_Property,
                        item.ProductNum, item.ProductNum_DisplayName, item.ProductNum_Enable, item.ProductNum_Show, item.ProductNum_Property,
                        item.Model, item.Model_DisplayName, item.Model_Enable, item.Model_Show, item.Model_Property, item.RecordElement, item.RecordElement_DisplayName, item.RecordElement_Enable,
                        item.RecordElement_Show, item.RecordElement_Property, item.RecordItem, item.RecordItem_DisplayName, item.RecordItem_Enable, item.RecordItem_Show, item.RecordItem_Property,
                        item.ToolUsed, item.ToolUsed_DisplayName, item.ToolUsed_Enable, item.ToolUsed_Show, item.ToolUsed_Property, item.AbnormalRecord, item.AbnormalRecord_DisplayName,
                        item.AbnormalRecord_Enable, item.AbnormalRecord_Show, item.AbnormalRecord_Property, item.Certificate, item.Certificate_DisplayName, item.Certificate_Enable,
                        item.Certificate_Show, item.Certificate_Property, item.SecondToolUsed, item.SecondToolUsed_DisplayName, item.SecondToolUsed_Enable, item.SecondToolUsed_Show,
                        item.SecondToolUsed_Property, item.ThirdToolUsed, item.ThirdToolUsed_DisplayName, item.ThirdToolUsed_Enable, item.ThirdToolUsed_Show, item.ThirdToolUsed_Property,
                        item.ParamCode, item.ParamCode_DisplayName, item.ParamCode_Enable, item.ParamCode_Show, item.ParamCode_Property
                        );
                        if (item.InspectionSignature != null)
                        {
                            cFormbase.InspectionSignature = cFormbase.SetInspectionSignature(item.InspectionSignature);
                        }
                        if (item.RecordRequirements != null)
                        {
                            cFormbase.RecordRequirements = cFormbase.SetRecordRequirements(item.RecordRequirements);
                        }
                        if (item.MultiMedia != null)
                        {
                            cFormbase.MultiMedia = cFormbase.SetMultiMedia(item.MultiMedia);
                        }
                        if (item.MeasuredResult != null)
                        {
                            cFormbase.MeasuredResult = cFormbase.SetMeasuredResult(item.MeasuredResult);
                        }
                        if (item.Environment != null)
                        {
                            cFormbase.Environment = cFormbase.SetEnvironment(item.Environment);
                        }
                        _convertFormBaseEntity.Insert(cFormbase);
                    }
                    #endregion

                    var bopNode = _bopNodeRepository.GetAll().Where(d => d.TechniqueEntityId == sourceId).FirstOrDefault();
                    if (bopNode != null)
                    {
                        dicMap.Add(bopNode.Id, tech.Id);
                        //更改关系表
                        var lineList = _processLineRepository.GetAll().Where(d => dicMap.Keys.Contains(d.PPtr));
                        foreach (var item in lineList)
                        {
                            if (dicMap.ContainsKey(item.PPtr))
                            {
                                item.PPtr = dicMap[item.PPtr];

                            }
                            if (dicMap.ContainsKey(item.From))
                            {
                                item.From = dicMap[item.From];

                            }
                            if (dicMap.ContainsKey(item.To))
                            {
                                item.To = dicMap[item.To];
                            }
                            item.Id = new Guid();
                            item.BopDescId = null;
                            _processLineRepository.Insert(item);
                        }

                    }
                    if (newTechId != null && newTechId != Guid.Empty)
                    {
                        var tempRe = _relationalCorrespondRepository.FirstOrDefault(d => d.FormerId == sourceId && d.RelationalType == 1);
                        if (tempRe != null)
                        {
                            tempRe.GoalId = newTechId;
                            tempRe.RelationalType = 1;
                            _relationalCorrespondRepository.Update(tempRe);
                        }
                        else
                        {
                            RelationalCorrespond relational = new RelationalCorrespond();
                            relational.FormerId = sourceId;
                            relational.GoalId = newTechId;
                            relational.RelationalType = 1;
                            _relationalCorrespondRepository.Insert(relational);
                        }

                        return tree;
                    }
                    else
                    {
                        return new TreeClass();
                    }
                }
                else
                {

                    TreeClass tree = new TreeClass();
                    tree.Id = newTech.Id;
                    tree.ParentId = Guid.Empty;
                    tree.NodeDrawingNo = newTech.TechniqueNumber;
                    tree.NodeName = newTech.TechniqueName;
                    tree.NodeLevel = 0;
                    tree.Edition = newTech.Edition;
                    var processesList = _processesEntityRepository.GetAllIncluding(p => p.WorkStepEntities).Where(p => p.TechniqueEntityId == newTech.Id).OrderBy(n => n.ProcessesSequence);
                    //获取工序和工步的信息，并做相应的排序
                    //循环遍历，往Node里面赋值
                    foreach (var item in processesList)
                    {
                        TreeClass treeProcessNode = new TreeClass();
                        treeProcessNode.Id = item.Id;
                        treeProcessNode.ParentId = item.TechniqueEntityId;
                        treeProcessNode.NodeDrawingNo = "工序" + item.ProcessesSequence.ToString() + " ";
                        treeProcessNode.NodeName = item.ProcessesName;
                        treeProcessNode.NodeLevel = 8;
                        item.WorkStepEntities = item.WorkStepEntities.OrderBy(r => r.WorkStepNumber).ToList();
                        //查询工步
                        foreach (var witem in item.WorkStepEntities)
                        {
                            TreeClass wtree = new TreeClass();
                            wtree.Id = witem.Id;
                            wtree.ParentId = item.Id;
                            wtree.NodeDrawingNo = "工步" + item.ProcessesSequence.ToString();// + "-"+ witem.WorkStepNumber.ToString();
                            wtree.NodeName = witem.WorkStepNumber.ToString();//witem.WorkStepName  这个值数据库有问题
                            wtree.NodeLevel = 9;
                            treeProcessNode.children.Add(wtree);
                        }
                        tree.children.Add(treeProcessNode);
                    }
                    return tree;
                }
            }
            else
            {
                return new TreeClass();
            }
        }
        #region 工序信息增删改查
        /// <summary>
        /// 根据Id获取单个工序信息
        /// </summary>
        /// <param name="guid"></param>
        /// <returns></returns>
        public ModifyProcessesDto GetModifyProcessesById(Guid guid)
        {
            var tempProcess = _processesEntityRepository.FirstOrDefault(d => d.Id == guid);
            if (tempProcess != null)
            {
                return ObjectMapper.Map<ModifyProcessesDto>(tempProcess);
            }
            else
            {
                return new ModifyProcessesDto();
            }
        }
        /// <summary>
        /// 新增/修改工序信息
        /// </summary>
        /// <param name="processesDto"></param>
        public ResultMessage InsertOrUpdateProcesses(ModifyProcessesDto processesDto)
        {
            ResultMessage resultMessage = new ResultMessage();
            try
            {
                //if (processesDto.ProcessesSequence > 0)
                //{
                //    var proEntitys = _processesEntityRepository.GetAll().Where(d => d.ProcessesSequence >= processesDto.ProcessesSequence&&d.TechniqueEntityId== processesDto.TechniqueEntityId).OrderBy(d=>d.ProcessesSequence).ToList();
                //    int tempPos = processesDto.ProcessesSequence + 1;
                //    for (int i = 0; i < proEntitys.Count(); i++)
                //    {
                //        proEntitys[i].ProcessesSequence = tempPos;
                //        tempPos++;
                //        _processesEntityRepository.Update(proEntitys[i]);
                //    }
                //}
                if (processesDto.Id != Guid.Empty && processesDto.Id != null)
                {
                    var process = _processesEntityRepository.Get(processesDto.Id.Value);
                    _iOperationHistoryAppService.InsertOperationLogNew(process.TechniqueEntityId, OperationHistory.BusinessTypes.Bop变更管理, OperationHistory.OperationTypes.修改工序, "【修改工序】" + "原工序: 工序名称:" + process.ProcessesName + ",工序序号:" + process.ProcessesSequence.ToString() + ",工序描述:" + process.ProcessesExplain + ",更改为: 工序名称:" + processesDto.ProcessesName + ",工序序号:" + processesDto.ProcessesSequence.ToString() + ",工序描述:" + processesDto.ProcessesExplain + "");

                    var proList = _processesEntityRepository.GetAll().Where(d => d.TechniqueEntityId == processesDto.TechniqueEntityId).Where(d => d.Id != processesDto.Id).OrderBy(d => d.ProcessesSequence).ToList();
                    process.ProcessesName = processesDto.ProcessesName;

                    string url = ConfigHelper.GetAppSetting("App", "GetAppUrl");
                    if (!string.IsNullOrEmpty(processesDto.ProcessesExplain))
                    {
                        processesDto.ProcessesExplain = processesDto.ProcessesExplain.Replace(url + @"/", "../");
                    }
                    process.ProcessesExplain = processesDto.ProcessesExplain;
                    process.TechniqueEntityId = processesDto.TechniqueEntityId;
                    var count = proList.Count(d => d.ProcessesSequence <= processesDto.ProcessesSequence);
                    if (processesDto.ProcessesSequence == 0)
                    {
                        processesDto.ProcessesSequence = 1;
                    }
                    if (processesDto.ProcessesSequence > proList.Count)
                    {
                        processesDto.ProcessesSequence = proList.Count + 1;
                    }
                    proList.Insert(processesDto.ProcessesSequence - 1, process);
                    for (int i = 0; i < proList.Count; i++)
                    {
                        proList[i].ProcessesSequence = i + 1;
                        _processesEntityRepository.Update(proList[i]);
                    }
                }
                else
                {
                    ProcessesEntity processes = new ProcessesEntity();
                    processes.ProcessesName = processesDto.ProcessesName;
                    processes.ProcessesSequence = processesDto.ProcessesSequence;
                    string url = ConfigHelper.GetAppSetting("App", "GetAppUrl");
                    if (!string.IsNullOrEmpty(processesDto.ProcessesExplain))
                    {
                        processesDto.ProcessesExplain = processesDto.ProcessesExplain.Replace(url + @"/", "../");
                    }
                    processes.ProcessesExplain = processesDto.ProcessesExplain;
                    processes.TechniqueEntityId = processesDto.TechniqueEntityId;
                    var proList = _processesEntityRepository.GetAll().Where(d => d.TechniqueEntityId == processesDto.TechniqueEntityId).OrderBy(d => d.ProcessesSequence).ToList();
                    //var count = proList.Count(d => d.ProcessesSequence < processesDto.ProcessesSequence);
                    //proList.Insert(count, processes);
                    if (processesDto.ProcessesSequence == 0)
                    {
                        processesDto.ProcessesSequence = 1;
                    }
                    if (processesDto.ProcessesSequence > proList.Count)
                    {
                        processesDto.ProcessesSequence = proList.Count + 1;
                    }
                    proList.Insert(processesDto.ProcessesSequence - 1, processes);
                    for (int i = 0; i < proList.Count; i++)
                    {
                        proList[i].ProcessesSequence = i + 1;
                        if (proList[i].Id == Guid.Empty || proList[i].Id == null)
                        {
                            _processesEntityRepository.Insert(proList[i]);
                        }
                        else
                        {
                            _processesEntityRepository.Update(proList[i]);
                        }

                    }
                    _iOperationHistoryAppService.InsertOperationLogNew(processes.TechniqueEntityId, OperationHistory.BusinessTypes.Bop变更管理, OperationHistory.OperationTypes.新增工序, "【新增工序】" + ": 工序名称:" + processes.ProcessesName + ",工序序号:" + processes.ProcessesSequence.ToString());
                }
                resultMessage.code = 0;
                return resultMessage;
            }
            catch (Exception ex)
            {
                resultMessage.code = 1;
                resultMessage.Message = ex.Message;
                return resultMessage;
            }
        }
        /// <summary>
        /// 根据Id删除工序信息
        /// </summary>
        /// <param name="guid"></param>
        public ResultMessage DeletdProcessById(Guid guid)
        {
            ResultMessage resultMessage = new ResultMessage();
            try
            {
                int count = _workStepEntityRepository.GetAll().Count(d => d.ProcessesEntityId == guid);
                if (count > 0)
                {
                    resultMessage.code = 1;
                    resultMessage.Message = "该节点下存在工步节点,请先删除该节点下的工步节点！";
                    return resultMessage;
                    //throw new UserFriendlyException("该节点下存在工步节点,请先删除该节点下的工步节点！");
                }
                else
                {
                    var temp = _processesEntityRepository.Get(guid);
                    var proList = _processesEntityRepository.GetAll().Where(d => d.TechniqueEntityId == temp.TechniqueEntityId).Where(d => d.Id != temp.Id).OrderBy(d => d.ProcessesSequence).ToList();
                    for (int i = 0; i < proList.Count; i++)
                    {
                        proList[i].ProcessesSequence = i + 1;
                        _processesEntityRepository.Update(proList[i]);
                    }
                    _processesEntityRepository.Delete(temp);
                    _iOperationHistoryAppService.InsertOperationLogNew(temp.TechniqueEntityId, OperationHistory.BusinessTypes.Bop变更管理, OperationHistory.OperationTypes.删除工序, "【删除工序】" + ": 工序名称:" + temp.ProcessesName + ",工序序号:" + temp.ProcessesSequence.ToString());
                }
                resultMessage.code = 0;
                return resultMessage;
            }
            catch (Exception ex)
            {
                resultMessage.code = 1;
                resultMessage.Message = ex.Message;
                return resultMessage;
            }
        }

        #endregion

        #region 工步信息CRUD
        /// <summary>
        /// 根据Id查询工步信息
        /// </summary>
        /// <param name="guid"></param>
        /// <returns></returns>
        public ModifyWorkingStepDto GetModifyWorkingStepById(Guid guid)
        {
            var tempWorkingStep = _workStepEntityRepository.FirstOrDefault(d => d.Id == guid);
            if (tempWorkingStep != null)
            {
                return ObjectMapper.Map<ModifyWorkingStepDto>(tempWorkingStep);
            }
            else
            {
                return new ModifyWorkingStepDto();
            }
        }
        /// <summary>
        /// 新增/修改工序信息
        /// </summary>
        /// <param name="workingStepDto"></param>
        public ResultMessage InsertOrUpdateWorkingStep(ModifyWorkingStepDto workingStepDto)
        {
            ResultMessage resultMessage = new ResultMessage();
            try
            {
                //if (workingStepDto.WorkStepNumber > 0)
                //{
                //    var workSteps = _workStepEntityRepository.GetAll().Where(d => d.WorkStepNumber >= workingStepDto.WorkStepNumber&&d.ProcessesEntityId== workingStepDto.ProcessesEntityId).OrderBy(d => d.WorkStepNumber).ToList();
                //    int tempPos = workingStepDto.WorkStepNumber + 1;
                //    for (int i = 0; i < workSteps.Count(); i++)
                //    {
                //        workSteps[i].WorkStepNumber = tempPos;
                //        tempPos++;
                //        _workStepEntityRepository.Update(workSteps[i]);
                //    }

                //}
                if (workingStepDto.Id != Guid.Empty && workingStepDto.Id != null)
                {
                    var work = _workStepEntityRepository.GetAll().Where(d => d.Id == workingStepDto.Id.Value).FirstOrDefault();
                    var temp = _processesEntityRepository.Get(work.ProcessesEntityId);
                    if (work.WorkStepNumber != workingStepDto.WorkStepNumber || work.WorkStepName != workingStepDto.WorkDetails || work.WorkDetails != work.WorkDetails)
                    {
                        _iOperationHistoryAppService.InsertOperationLogNew(work.TechniqueEntityId, OperationHistory.BusinessTypes.Bop变更管理, OperationHistory.OperationTypes.修改工步, "工序" + temp.ProcessesSequence.ToString() + "修改" + "工步" + work.WorkStepNumber.ToString() + ",原工步信息为:工步序号:" + work.WorkStepNumber.ToString() + ",工步内容:" + work.WorkStepName + ",修改为:工步序号:" + workingStepDto.WorkStepNumber.ToString() + "工步内容:" + workingStepDto.WorkDetails);
                    }
                    work.WorkStepNumber = workingStepDto.WorkStepNumber;
                    work.WorkStepName = workingStepDto.WorkDetails;
                    work.WorkDetails = workingStepDto.WorkDetails;
                    var proList = _workStepEntityRepository.GetAll().Where(d => d.ProcessesEntityId == work.ProcessesEntityId).Where(d => d.Id != workingStepDto.Id).OrderBy(d => d.WorkStepNumber).ToList();
                    //var count = proList.Count(d => d.WorkStepNumber <= workingStepDto.WorkStepNumber);

                    if (workingStepDto.WorkStepNumber == 0)
                    {
                        workingStepDto.WorkStepNumber = 1;
                    }
                    if (workingStepDto.WorkStepNumber > proList.Count)
                    {
                        workingStepDto.WorkStepNumber = proList.Count + 1;
                    }
                    proList.Insert(workingStepDto.WorkStepNumber - 1, work);
                    for (int i = 0; i < proList.Count; i++)
                    {
                        proList[i].WorkStepNumber = i + 1;
                        _workStepEntityRepository.Update(proList[i]);
                    }
                }
                else
                {
                    WorkStepEntity workStepEntity = new WorkStepEntity();
                    workStepEntity.WorkStepNumber = workingStepDto.WorkStepNumber;
                    workStepEntity.WorkStepName = workingStepDto.WorkDetails;
                    workStepEntity.TechniqueEntityId = workingStepDto.TechniqueEntityId;
                    workStepEntity.ProcessesEntityId = workingStepDto.ProcessesEntityId;

                    var proList = _workStepEntityRepository.GetAll().Where(d => d.ProcessesEntityId == workingStepDto.ProcessesEntityId).OrderBy(d => d.WorkStepNumber).ToList();
                    //var count = proList.Count(d => d.WorkStepNumber < workingStepDto.WorkStepNumber);
                    //proList.Insert(count, workStepEntity);
                    if (workingStepDto.WorkStepNumber == 0)
                    {
                        workingStepDto.WorkStepNumber = 1;
                    }
                    if (workingStepDto.WorkStepNumber > proList.Count)
                    {
                        workingStepDto.WorkStepNumber = proList.Count + 1;
                    }
                    proList.Insert(workingStepDto.WorkStepNumber - 1, workStepEntity);
                    for (int i = 0; i < proList.Count; i++)
                    {
                        proList[i].WorkStepNumber = i + 1;
                        if (proList[i].Id == Guid.Empty || proList[i].Id == null)
                        {
                            _workStepEntityRepository.Insert(proList[i]);
                        }
                        else
                        {
                            _workStepEntityRepository.Update(proList[i]);
                        }
                    }
                    var temp = _processesEntityRepository.Get(workingStepDto.ProcessesEntityId);
                    _iOperationHistoryAppService.InsertOperationLogNew(workStepEntity.TechniqueEntityId, OperationHistory.BusinessTypes.Bop变更管理, OperationHistory.OperationTypes.新增工步, "工序" + temp.ProcessesSequence.ToString() + "新增" + "工步" + workStepEntity.WorkStepNumber.ToString());
                }
                resultMessage.code = 0;
                return resultMessage;
            }
            catch (Exception ex)
            {
                resultMessage.code = 1;
                resultMessage.Message = ex.Message;
                return resultMessage;
            }
        }
        /// <summary>
        /// 删除工步
        /// </summary>
        /// <param name="guid"></param>
        public ResultMessage DeletdWorkStepById(Guid guid)
        {
            ResultMessage resultMessage = new ResultMessage();
            try
            {
                var loadList = _loadPieceRepository.GetAll().Where(d => d.WorkStepEntityId == guid).ToList();
                if (loadList.Count > 0)
                {
                    var loadIdList = loadList.Select(d => d.Id).ToList();
                    int tempCount = _storeStockContentRepsitory.GetAll().Count(d => loadIdList.Contains(d.LoadDetailsId.Value));
                    if (tempCount > 0)
                    {
                        resultMessage.code = 1;
                        resultMessage.Message = "该工步有已配套的物料,请先解除配套，然后删除该工步！";
                        return resultMessage;
                        //throw new UserFriendlyException("该工步有已配套的物料,请先解除配套，然后删除该工步！");
                    }
                }
                var workTemp = _workStepEntityRepository.Get(guid);

                var proList = _workStepEntityRepository.GetAll().Where(d => d.ProcessesEntityId == workTemp.ProcessesEntityId).Where(d => d.Id != workTemp.Id).OrderBy(d => d.WorkStepNumber).ToList();
                for (int i = 0; i < proList.Count; i++)
                {
                    proList[i].WorkStepNumber = i + 1;
                    _workStepEntityRepository.Update(proList[i]);
                }

                _workStepEntityRepository.Delete(workTemp);
                var tempProcess = _processesEntityRepository.Get(workTemp.ProcessesEntityId);
                string processNmae = "工序" + tempProcess.ProcessesSequence.ToString();
                _iOperationHistoryAppService.InsertOperationLogNew(workTemp.TechniqueEntityId, OperationHistory.BusinessTypes.Bop变更管理, OperationHistory.OperationTypes.删除工步, processNmae + "删除" + "原工步" + workTemp.WorkStepNumber.ToString());
                resultMessage.code = 0;
                return resultMessage;
            }
            catch (Exception ex)
            {
                resultMessage.code = 1;
                resultMessage.Message = ex.Message;
                return resultMessage;
            }
        }

        #endregion
        /// <summary>
        /// 获取变更类型
        /// </summary>
        /// <returns></returns>
        public List<Sys_Code> GetChangeType(string desc)
        {
            var codeList = _sysCodeRepository.GetAll().Where(d => d.PPtr == Guid.Empty && d.Description == desc).FirstOrDefault();
            if (codeList != null)
            {

                var temp = _sysCodeRepository.GetAll().Where(d => d.PPtr == codeList.Id).OrderBy(d => d.Sort).ToList();
                return temp;
            }
            else
            {
                return new List<Sys_Code>();
            }
        }



        private List<WorkLabelOutPut> GetEnumDescByTemp<T>(T t)
        {
            List<WorkLabelOutPut> temp = new List<WorkLabelOutPut>();
            foreach (int myCode in Enum.GetValues(typeof(T)))
            {
                WorkLabelOutPut work = new WorkLabelOutPut();
                string strName = Enum.GetName(typeof(T), myCode);//获取名称
                work.Value = myCode;
                work.Label = strName;
                temp.Add(work);
            }
            return temp;
        }
        /// <summary>
        /// 获取工艺规程的枚举描述信息 1阶段标记 2工艺规程类型 3 纸质形式  4 文件密级
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        public List<WorkLabelOutPut> GetEnumDescs(int input)
        {
            List<WorkLabelOutPut> dicTemp = new List<WorkLabelOutPut>();
            switch (input)
            {
                case 1:
                    StageSigns temp1 = StageSigns.D;
                    dicTemp = GetEnumDescByTemp(temp1);
                    break;
                case 2:
                    TechniqueTypes temp2 = TechniqueTypes.专用;
                    dicTemp = GetEnumDescByTemp(temp2);
                    break;
                case 3:
                    Shapes temp3 = Shapes.白图;
                    dicTemp = GetEnumDescByTemp(temp3);
                    break;
                case 4:
                    SecretDegrees temp4 = SecretDegrees.内部;
                    dicTemp = GetEnumDescByTemp(temp4);
                    break;
                default:
                    break;
            }
            return dicTemp;
        }
        //新增或者修改动态表数据
        public async Task<ResultMessage> InsertOrUpdateMoadifTable(WorkStepOutDto workStep, string tableName, Guid mocId)
        {
            //动态表数据无非就三种  1 新增 2 修改 3 删除 然后日志记录下来就可以
            ResultMessage resultMessage = new ResultMessage();
            resultMessage = await _processManage.InsertOrUpdateTable(workStep, tableName, mocId);
            return resultMessage;
        }

        /// <summary>
        /// 根据枚举获取枚举描述信息
        /// </summary>
        /// <param name="parm"></param>
        /// <returns></returns>
        private static string GetEnumDesc(System.Enum parm)
        {
            FieldInfo enumInfo = parm.GetType().GetField(parm.ToString());
            if (enumInfo == null)
            {
                return "";
            }
            DescriptionAttribute[] enumAttributes
                = (DescriptionAttribute[])enumInfo.GetCustomAttributes(typeof(DescriptionAttribute), false);
            if (enumAttributes.Length > 0)
            {
                return enumAttributes[0].Description;
            }
            return parm.ToString();
        }
    }


}
